from typing import List

from fastapi import Request
from sqlalchemy.ext.asyncio import AsyncSession

from exceptions.exception import ServiceException
from module_admin.entity.vo.common_vo import CrudResponseModel
from module_basics.dao.log_dao import ContrastLogDao
from module_basics.entity.vo.log_vo import ContrastLogPageQueryModel, ContrastLogModel, DeleteContrastLogModel
from utils.common_util import export_list2excel


class ContrastLogService:
    """
    对比日志管理模块服务层
    """

    @classmethod
    async def get_contrast_log_list_services(
            cls, query_db: AsyncSession, query_object: ContrastLogPageQueryModel, is_page: bool = False
    ):
        """
        获取对比日志列表信息service

        :param query_db: orm对象
        :param query_object: 查询参数对象
        :param is_page: 是否开启分页
        :return: 操作日志列表信息对象
        """
        contrast_log_list_result = await ContrastLogDao.get_contrast_log_list(query_db, query_object, is_page)

        return contrast_log_list_result

    @classmethod
    async def add_contrast_log_services(cls, query_db: AsyncSession, page_object: ContrastLogModel):
        """
        新增对比日志service

        :param query_db: orm对象
        :param page_object: 新增操作日志对象
        :return: 新增操作日志校验结果
        """
        try:
            await ContrastLogDao.add_contrast_log_dao(query_db, page_object)
            await query_db.commit()
            return CrudResponseModel(is_success=True, message='新增成功')
        except Exception as e:
            await query_db.rollback()
            raise e

    @classmethod
    async def delete_operation_log_services(cls, query_db: AsyncSession, page_object: DeleteContrastLogModel):
        """
        删除操作日志信息service

        :param query_db: orm对象
        :param page_object: 删除操作日志对象
        :return: 删除操作日志校验结果
        """
        if page_object.ids:
            id_list = page_object.ids.split(',')
            try:
                for d_id in id_list:
                    await ContrastLogDao.delete_contrast_log_dao(query_db, ContrastLogModel(id=d_id))
                await query_db.commit()
                return CrudResponseModel(is_success=True, message='删除成功')
            except Exception as e:
                await query_db.rollback()
                raise e
        else:
            raise ServiceException(message='传入对比日志id为空')

    @classmethod
    async def clear_operation_log_services(cls, query_db: AsyncSession):
        """
        清除操作日志信息service

        :param query_db: orm对象
        :return: 清除操作日志校验结果
        """
        try:
            await ContrastLogDao.clear_contrast_log_dao(query_db)
            await query_db.commit()
            return CrudResponseModel(is_success=True, message='清除成功')
        except Exception as e:
            await query_db.rollback()
            raise e

    @classmethod
    async def export_contrast_log_list_services(cls, request: Request, contrast_log_list: List):
        """
        导出操作日志信息service

        :param request: Request对象
        :param contrast_log_list: 操作日志信息列表
        :return: 操作日志信息对应excel的二进制数据
        """
        # 创建一个映射字典，将英文键映射到中文键
        mapping_dict = {
            'id': '对比日志主键',
            'source_file_name': '原文件名称',
            'source_file_path': '原文件地址',
            'target_file_name': '目标文件名称',
            'target_file_path': '目标文件地址',
            'operator': '操作人员',
            'host_ip': '主机地址',
            'operating_location': '操作地点',
            'request_param': '请求参数',
            'json_result': '返回参数',
            'status': '操作状态（0正常 1异常）',
            'operation_time': '操作时间',
            'cost_time': '消耗时间',
        }

        data = contrast_log_list
        for item in data:
            if item.get('status') == 0:
                item['status'] = '成功'
            else:
                item['status'] = '失败'
        binary_data = export_list2excel(data)

        return binary_data
